<?php
require_once ('./class/H.class.php');
require_once ('./class/database.class.php');
require_once ("./class/Snoopy.class.php");
$snoopy = new Snoopy();
//_categories();
_getImages();
//_subCategory();

function _images($obj,$p){
    global $dbm,$snoopy;
    $url = "https://api2.paixin.com/albums/".$obj['sortby']."/medias?page=".$p."&size=45&sort=createdAt,desc";
    $snoopy->fetch($url);

    $data = json_decode($snoopy->getResults(),1);

    if(!empty($data['elements'])){
        foreach($data['elements'] as $k => $v){
            $dbm->insert('tb_imgs',[
                    'cid' => $obj['id'],
                    'url' => "https:".$v['image'],
                    'cdn' => "",
                    'isdel' => 0,
                    'ctime' => time(),
                    'w' => $v['width'],
                    'h' => $v['height'],
                    'pcid' => $obj['ctype']
                ]
            );
            echo $dbm->id()."-success-".chr(10);
        }
    } else {
        echo "already completes...".chr(10);
        return;
    }

    $p = $p + 1;
    _images($obj,$p);
}

function _getImages(){
    global $dbm;

    $listData = $dbm->select('tb_img_cat',['id','sortby','ctype'],['ctype[>]' => 0,"ORDER"=>['id'=>"ASC"]]);
    if(count($listData) == 0){
        echo "already completes...".chr(10);
        return;
    }

    foreach($listData as $lk => $lv){
         _images($lv,0);
         sleep(1);
    }
}

function _categories(){
    global $dbm,$snoopy;
    $url = "https://api2.paixin.com/albums/categories?types=6";
    $snoopy->fetch($url);
    $data = json_decode($snoopy->getResults(),1);
    foreach($data as $k => $v){
        $dbm->insert('tb_img_cat',[
                'name' => $v['name'],
                'sortby' => $v['id'],
            ]
        );
        echo $dbm->id()."-success-".chr(10);
    }
}

function _subCategory(){
    global $dbm,$snoopy;
    $listData = $dbm->select('tb_img_cat',['id','sortby'],["ORDER"=>['id'=>"ASC"]]);
    if(count($listData) == 0){
        echo "already completes...".chr(10);
        return;
    }
    foreach($listData as $lk => $lv){
        $url = "https://api2.paixin.com/albums/categories/".$lv['sortby']."?page=0&size=100&sort=createdAt%2Cdesc";
        $snoopy->fetch($url);
        $data = json_decode($snoopy->getResults(),1);

        if(!empty($data['elements'])){
            foreach($data['elements'] as $ele => $elv){
                $dbm->insert('tb_img_cat',[
                        'name' => $elv['name'],
                        'sortby' => $elv['id'],
                        'ctype' => $lv['id']
                    ]
                );
                echo $dbm->id()."-success-".chr(10);
            }
        }
    }
}
